import javax.swing.*;
import javax.swing.table.DefaultTableModel;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.sql.*;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class GoodsManageFrame extends JFrame {
    private JTable goodsTable;
    private DefaultTableModel tableModel;

    public GoodsManageFrame() {
        setTitle("货物管理");
        setSize(800, 500);
        setLocationRelativeTo(null);

        // 初始化表格模型
        tableModel = new DefaultTableModel();
        tableModel.addColumn("货物编号");
        tableModel.addColumn("货物名称");
        tableModel.addColumn("货物形态");
        tableModel.addColumn("最低库存");
        tableModel.addColumn("最高库存");
        tableModel.addColumn("货物型号");

        goodsTable = new JTable(tableModel);
        JScrollPane scrollPane = new JScrollPane(goodsTable);

        // 初始化按钮面板
        JPanel buttonPanel = new JPanel();
        JButton addBtn = new JButton("添加");
        JButton editBtn = new JButton("修改");
        JButton deleteBtn = new JButton("删除");
        JButton refreshBtn = new JButton("刷新");

        buttonPanel.add(addBtn);
        buttonPanel.add(editBtn);
        buttonPanel.add(deleteBtn);
        buttonPanel.add(refreshBtn);

        // 设置布局
        setLayout(new BorderLayout());
        add(scrollPane, BorderLayout.CENTER);
        add(buttonPanel, BorderLayout.SOUTH);

        // 加载初始数据
        loadGoodsData();

        // 设置按钮事件监听
        addBtn.addActionListener(e -> {
            new GoodsEditDialog(null).setVisible(true);
            loadGoodsData();
        });

        editBtn.addActionListener(e -> {
            int selectedRow = goodsTable.getSelectedRow();
            if (selectedRow >= 0) {
                String dno = (String) tableModel.getValueAt(selectedRow, 0);
                new GoodsEditDialog(dno).setVisible(true);
                loadGoodsData();
            } else {
                JOptionPane.showMessageDialog(this, "请选择要修改的行", "提示", JOptionPane.WARNING_MESSAGE);
            }
        });

        deleteBtn.addActionListener(e -> deleteGoods());
        refreshBtn.addActionListener(e -> loadGoodsData());
    }

    /**
     * 加载货物数据（使用动态SQL）
     */
    private void loadGoodsData() {
        tableModel.setRowCount(0); // 清空表格

        // 动态构建查询SQL
        String sql = "SELECT dno, dname, dtype, dmin, dmax, did FROM goods";

        try (Connection conn = DBUtil.getConnection();
             PreparedStatement pstmt = conn.prepareStatement(sql);
             ResultSet rs = pstmt.executeQuery()) {

            while (rs.next()) {
                tableModel.addRow(new Object[]{
                        rs.getString("dno"),
                        rs.getString("dname"),
                        rs.getString("dtype"),
                        rs.getInt("dmin"),
                        rs.getInt("dmax"),
                        rs.getString("did")
                });
            }
        } catch (SQLException e) {
            showErrorDialog("加载数据失败: " + e.getMessage());
            e.printStackTrace();
        }
    }

    /**
     * 删除货物（使用参数化SQL）
     */
    private void deleteGoods() {
        int selectedRow = goodsTable.getSelectedRow();
        if (selectedRow >= 0) {
            String dno = (String) tableModel.getValueAt(selectedRow, 0);

            int confirm = JOptionPane.showConfirmDialog(
                    this,
                    "确定要删除货物编号为 " + dno + " 的记录吗?",
                    "确认删除",
                    JOptionPane.YES_NO_OPTION);

            if (confirm == JOptionPane.YES_OPTION) {
                // 使用参数化SQL防止注入
                String sql = "DELETE FROM goods WHERE dno = ?";

                try (Connection conn = DBUtil.getConnection();
                     PreparedStatement pstmt = conn.prepareStatement(sql)) {

                    pstmt.setString(1, dno);
                    int affectedRows = pstmt.executeUpdate();

                    if (affectedRows > 0) {
                        JOptionPane.showMessageDialog(this, "删除成功");
                        loadGoodsData();
                    }
                } catch (SQLException e) {
                    showErrorDialog("删除失败: " + e.getMessage());
                    e.printStackTrace();
                }
            }
        } else {
            JOptionPane.showMessageDialog(this, "请选择要删除的行", "提示", JOptionPane.WARNING_MESSAGE);
        }
    }

    /**
     * 显示错误对话框
     */
    private void showErrorDialog(String message) {
        JOptionPane.showMessageDialog(this, message, "错误", JOptionPane.ERROR_MESSAGE);
    }
}

/**
 * 货物编辑对话框（使用动态SQL）
 */
class GoodsEditDialog extends JDialog {
    private JTextField dnoField, dnameField, dtypeField, dminField, dmaxField, didField;
    private boolean isEditMode;

    public GoodsEditDialog(String dno) {
        setTitle(dno == null ? "添加货物" : "修改货物");
        isEditMode = dno != null;

        setSize(400, 300);
        setModal(true);
        setLocationRelativeTo(null);

        // 初始化表单组件
        initFormComponents();

        if (isEditMode) {
            loadGoodsData(dno);
        }
    }

    /**
     * 初始化表单组件
     */
    private void initFormComponents() {
        JPanel panel = new JPanel(new GridLayout(6, 2, 5, 5));
        panel.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));

        panel.add(new JLabel("货物编号:"));
        dnoField = new JTextField();
        if (isEditMode) dnoField.setEditable(false);
        panel.add(dnoField);

        panel.add(new JLabel("货物名称:"));
        dnameField = new JTextField();
        panel.add(dnameField);

        panel.add(new JLabel("货物形态:"));
        dtypeField = new JTextField();
        panel.add(dtypeField);

        panel.add(new JLabel("最低库存:"));
        dminField = new JTextField();
        panel.add(dminField);

        panel.add(new JLabel("最高库存:"));
        dmaxField = new JTextField();
        panel.add(dmaxField);

        panel.add(new JLabel("货物型号:"));
        didField = new JTextField();
        panel.add(didField);

        // 添加按钮
        JButton saveBtn = new JButton("保存");
        saveBtn.addActionListener(this::saveGoods);

        JButton cancelBtn = new JButton("取消");
        cancelBtn.addActionListener(e -> dispose());

        JPanel buttonPanel = new JPanel(new FlowLayout(FlowLayout.CENTER, 10, 10));
        buttonPanel.add(saveBtn);
        buttonPanel.add(cancelBtn);

        add(panel, BorderLayout.CENTER);
        add(buttonPanel, BorderLayout.SOUTH);
    }

    /**
     * 加载货物数据
     */
    private void loadGoodsData(String dno) {
        // 使用参数化SQL
        String sql = "SELECT * FROM goods WHERE dno = ?";

        try (Connection conn = DBUtil.getConnection();
             PreparedStatement pstmt = conn.prepareStatement(sql)) {

            pstmt.setString(1, dno);

            try (ResultSet rs = pstmt.executeQuery()) {
                if (rs.next()) {
                    dnoField.setText(rs.getString("dno"));
                    dnameField.setText(rs.getString("dname"));
                    dtypeField.setText(rs.getString("dtype"));
                    dminField.setText(String.valueOf(rs.getInt("dmin")));
                    dmaxField.setText(String.valueOf(rs.getInt("dmax")));
                    didField.setText(rs.getString("did"));
                }
            }
        } catch (SQLException e) {
            showErrorDialog("加载数据失败: " + e.getMessage());
            e.printStackTrace();
        }
    }

    /**
     * 保存货物信息（使用动态SQL）
     */
    private void saveGoods(ActionEvent e) {
        // 收集表单数据
        String dno = dnoField.getText().trim();
        String dname = dnameField.getText().trim();
        String dtype = dtypeField.getText().trim();
        String dminStr = dminField.getText().trim();
        String dmaxStr = dmaxField.getText().trim();
        String did = didField.getText().trim();

        // 数据验证
        if (!validateInput(dno, dname, did, dminStr, dmaxStr)) {
            return;
        }

        int dmin = Integer.parseInt(dminStr);
        int dmax = Integer.parseInt(dmaxStr);

        // 动态构建SQL
        StringBuilder sqlBuilder = new StringBuilder();
        List<Object> params = new ArrayList<>();

        if (isEditMode) {
            sqlBuilder.append("UPDATE goods SET dname=?, dtype=?, dmin=?, dmax=?, did=? WHERE dno=?");
            Collections.addAll(params, dname, dtype, dmin, dmax, did, dno);
        } else {
            sqlBuilder.append("INSERT INTO goods (dno, dname, dtype, dmin, dmax, did) VALUES (?, ?, ?, ?, ?, ?)");
            Collections.addAll(params, dno, dname, dtype, dmin, dmax, did);
        }

        // 执行SQL
        try (Connection conn = DBUtil.getConnection();
             PreparedStatement pstmt = conn.prepareStatement(sqlBuilder.toString())) {

            for (int i = 0; i < params.size(); i++) {
                pstmt.setObject(i + 1, params.get(i));
            }

            int affectedRows = pstmt.executeUpdate();

            if (affectedRows > 0) {
                JOptionPane.showMessageDialog(this, "保存成功");
                dispose();
            }
        } catch (SQLException ex) {
            showErrorDialog("保存失败: " + ex.getMessage());
            ex.printStackTrace();
        }
    }

    /**
     * 验证输入数据
     */
    private boolean validateInput(String dno, String dname, String did, String dminStr, String dmaxStr) {
        if (dno.isEmpty() || dname.isEmpty() || did.isEmpty()) {
            showErrorDialog("货物编号、名称和型号不能为空");
            return false;
        }

        try {
            Integer.parseInt(dminStr);
            Integer.parseInt(dmaxStr);
        } catch (NumberFormatException e) {
            showErrorDialog("库存量必须为整数");
            return false;
        }

        return true;
    }

    /**
     * 显示错误对话框
     */
    private void showErrorDialog(String message) {
        JOptionPane.showMessageDialog(this, message, "错误", JOptionPane.ERROR_MESSAGE);
    }
}